<template>
  <div v-loading="loading">
    <div>
      <div class="area-header">
        <span class="area-header-title">{{ form.questionName }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm" style="margin-top: 25px;">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('客户名称')" prop="score">
              <el-select v-model="form.investId" :placeholder="$t('客户名称')" disabled clearable>
                <el-option
                  v-for="dict in lpBaseOption"
                  :key="dict.name"
                  :label="dict.name"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('填写时间')" prop="time">
              <el-date-picker
                v-model="form.time"
                clearable
                disabled
                style="width: 200px"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="$t('答题时间')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('总分')" prop="score">
              <el-input v-model="form.score" :placeholder="$t('总分')" disabled show-word-limit maxlength="32" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('对应结果')" prop="result">
              <dictSelect
                v-model="form.result"
                clearable
                disabled
                :placeholder="$t('对应结果')"
                dictionary="corresponding_results"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="area-header" style="margin-top: 15px">
          <span class="area-header-title">{{ $t('问题列表') }}</span>
        </div>
        <div v-for="(item, index) in questionList" :key="item.id" style="padding: 10px;line-height: 2;">
          <div>
            <span style="font-size: 14px;font-weight: bold;">{{ $t('问题') }}{{ index + 1 }}: {{ item.name }} ({{ item.isMultipleChoice === 'Y' ? $t('多选') : $t('单选') }})</span>
            <!-- 多选 -->
            <div v-if="item.isMultipleChoice === 'Y'">
              <el-checkbox-group v-model="item.checkList" style="display: inline-grid;" @change="changeCheck(item.checkList, index)">
                <el-checkbox v-for="(sub, ins) in item.answerKeyList" :key="sub.id + index + ins" :label="sub.answer" style="font-weight: 350;font-size: 12px;" />
              </el-checkbox-group>
            </div>
            <!-- 单选 -->
            <div v-else>
              <el-radio-group v-model="item.radio" style="display: inline-grid;" @change="changeRadio(item.radio, index)">
                <el-radio v-for="(sub, ins) in item.answerKeyList" :key="sub.id + index + ins" :label="sub.answer" style="margin: 4px 0 4px 0;font-weight: 350;font-size: 12px;">{{ $t(sub.answer) }}</el-radio>
              </el-radio-group>
            </div>
            <div v-if="item.freedom === 'Y'">
              <el-input v-model="item.remark" type="textarea" :autosize="{ minRows: 1, maxRows: 2 }" maxlength="2000" show-word-limit :placeholder="$t('补充说明')" style="min-height: 33px;height: 33px;border-top: none;border-left: none;border-right: none;border-radius: 0;" @change="finalScoring" />
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <div v-if="editStatus" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="lp:investigation" />
    </div>
  </div>
</template>

<script>

import {
  getLpQuestionnaireInvestigation,
  saveProblem
} from '@/api/fund/questionnaire/investigation/lpQuestionnaireInvestigation'
import {
  findListByQuestionnaireId,
  getLpBaseByType
} from '@/api/fund/questionnaire/settings/questionnaireQuestion/lpQuestionnaireQuestion'
import {
  LpQuestionnaireScoreSettingsList
} from '@/api/fund/questionnaire/settings/questionnaireSet/lpQuestionnaireSet'

export default {
  data() {
    return {
      // 表单参数
      form: {},
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {},
      checkList: [],
      // 问题列表
      questionList: [],
      // 客户名称字段
      lpBaseOption: [],
      // 结果字典
      resultOption: [],
      editStatus: true
    }
  },
  watch: {
    'form.investType': {
      handler(val) {
        getLpBaseByType(val).then(response => {
          this.lpBaseOption = response.data
        })
      }
    },
    'form.dataId': {
      handler(val) {
        // 获取对应结果字典
        LpQuestionnaireScoreSettingsList({ questionnaireId: val }).then(response => {
          this.resultOption = response.rows
        })
      }
    }
  },
  created() {
  },
  methods: {
    // 初始化数据
    init(data, editStatus) {
      this.editStatus = editStatus
      if (data != null && data.id !== undefined && data.questionNameId !== null && data.questionNameId !== undefined) {
        this.loading = true
        // 加载出所有问题
        findListByQuestionnaireId(data.questionNameId).then(response => {
          this.questionList = response.data
          this.questionList.forEach(item => {
            item.checkList = []
          })
          // 获取填写好的答案
          getLpQuestionnaireInvestigation(data.id).then(response2 => {
            this.form = response2.data
            // 将填写的数据回回显到问题上
            this.echoToTheProblem()
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 将填写的数据回回显到问题上
    echoToTheProblem() {
      if (this.form.problemList !== undefined && this.form.problemList !== null) {
        this.form.problemList.forEach(item => {
          this.questionList.forEach(sub => {
            if (item.questionId === sub.id) {
              if (sub.isMultipleChoice === 'Y') {
                sub.checkList = JSON.parse(item.answer)
              } else {
                sub.radio = item.answer
              }
              sub.remark = item.remark
            }
          })
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        question: undefined,
        answer: undefined,
        problemList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.problemOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.problemOpen !== undefined) {
        this.$parent.$parent.problemOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    changeCheck(val, index) {
      this.$nextTick(() => {
        this.$set(this.questionList[index], 'checkList', val)
        this.$forceUpdate()

        // 计算总分
        this.finalScoring(index)
      })
    },
    changeRadio() {
      // 计算总分
      this.finalScoring()
    },
    /** 计算总分, 判断对应结果, 安排好要保存的值 */
    finalScoring() {
      var score = 0
      var arr = []
      this.questionList.forEach(item => {
        item.answerKeyList.forEach(sub => {
          // 单选还是多选
          if (item.isMultipleChoice === 'Y') {
            if (item.checkList.includes(sub.answer)) {
              score += Number(sub.score)
            }
          } else {
            if (sub.answer === item.radio) {
              score += Number(sub.score)
            }
          }
        })
        var obj = { questionId: item.id }
        if (item.isMultipleChoice === 'Y') {
          obj.answer = JSON.stringify(item.checkList)
        } else {
          obj.answer = item.radio
        }
        obj.remark = item.remark
        if (obj.answer || obj.remark) {
          arr.push(obj)
        }
      })
      this.form.score = score
      this.form.problemList = arr

      // 根据分数判断结果
      if (this.resultOption !== null) {
        this.resultOption.forEach(item => {
          if (item.startScore <= this.form.score && this.form.score <= item.endScore) {
            this.form.result = item.result
          }
        })
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveProblem(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-textarea__inner {
  display: block;
  border-top: none !important;
  border-left: none !important;
  border-right: none !important;
  border-radius: 0px !important;
  resize: vertical;
  padding: 5px 15px;
  line-height: 1.5;
  box-sizing: border-box;
  width: 100%;
  font-size: inherit;
  color: #606266;
  background-color: #fff;
  background-image: none;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}
</style>
